<?php
/**
* Email communication
*
*
*
*/

class Letter
{
	var $data = array();
	var $subject;
	var $message;
	var $attaches = array();
	
	function read($id, $fid=0)
	{		
		global $CI;

		if (!$fid)
		{
			$a = $CI->session->userdata('admin_auth_logged');
			$fid = $a['admin_id'];		
		}
		
		// sql
		if (is_string($id))	
		{
			$CI->db->join(TEMPLATE_TYPES, TEMPLATE_TYPES.'.'.TEMPLATE_TYPES_TEMPLATE_TYPE_ID.'='.TEMPLATES.'.'.TEMPLATES_TEMPLATE_TYPE_ID);
			$CI->db->where(TEMPLATE_TYPES.'.'.TEMPLATE_TYPES_NAME, $id);
			$q = $CI->db->get_where(TEMPLATES, array(TEMPLATES_FRANCHISE_ID=>$fid));
		}
		else 
			$q = $CI->db->get_where(TEMPLATES, array(TEMPLATES_FRANCHISE_ID=>$fid, TEMPLATES_TEMPLATE_TYPE_ID=>$id));
		$e = $q->row();
		$this->subject = $e?$e->{TEMPLATES_SUBJECT}:'';
		if ($this->subject == 'Re') $this->subject = '';
		$this->message = $e?$e->{TEMPLATES_BODY}:'';

		//$this->franchise_name();
	}
	
	function franchise_name()
	{
		global $CI;
		$a = $CI->session->userdata('admin_auth_logged');
		$this->add('franchisee_name', $a['name']);
	}
	
	function admin_id()
	{
		global $CI;
		$a = $CI->session->userdata('admin_auth_logged');
		return $a['admin_id'];
	}
	
	function parse()
	{
		$CI =& get_instance();
		
		foreach ($this->data as $key => $val)
		{
			if (is_array($val))
			{
				$this->message = $CI->parser->_parse_pair($key, $val, $this->message);		
				$this->subject = $CI->parser->_parse_pair($key, $val, $this->subject);		
			}
			else
			{
				$this->message = $CI->parser->_parse_single($key, (string)$val, $this->message);
				$this->subject = $CI->parser->_parse_single($key, (string)$val, $this->subject);
			}
		}
	}
	
	function add($name, $value)
	{
		$this->data[$name] = $value;
	}
	
	function send($from, $to)
	{
		$this->parse();
		$this->data = array();
		
		global $CI;
		$CI->load->library('email');
        $CI->email->clear();
		//$config['protocol'] = 'mail';
		//$config['mailtype'] = 'html';
		//$config['charset'] = 'utf-8';
		//$config['wordwrap'] = TRUE;
		
		//$CI->email->initialize($config);
		
		$CI->email->from($from);
		$CI->email->to($to);
				
		$CI->email->subject($this->subject);
		$CI->email->message($this->message);
        foreach($this->attaches as $f){
            if(@file_exists($f))
                $CI->email->attach($f);
        }
        
		return @$CI->email->send();
		
		//$CI->email->print_debugger();	
	}
    
    function attach($file){
        $this->attaches[] = trim($file);
    }
}